package com.gzy.wb.controller;


import com.gzy.wb.controller.para.MyLogPara;
import com.gzy.wb.controller.para.UserCreatePara;
import com.gzy.wb.controller.para.UserUpdatePara;
import com.gzy.wb.core.Page;
import com.gzy.wb.core.R;
import com.gzy.wb.model.MyLog;
import com.gzy.wb.model.User;
import com.gzy.wb.server.UserServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserServer userServer;

    @Secured("ROLE_ADMIN")
    @GetMapping("/page")
    R<org.springframework.data.domain.Page<User>> page(@AuthenticationPrincipal UserDetails user, Long page, Long size){
        org.springframework.data.domain.Page<User> userByPage = userServer.findUserByPage(page-1, size);

        return new R<>(){{
            setData(userByPage);
        }};
    }
    @Secured("ROLE_ADMIN")
    @GetMapping("/{id}")
    R<User> show(@PathVariable Integer id , @AuthenticationPrincipal UserDetails user){
        User v = userServer.show(id);
        return new R<>(){{
            setData(v);
        }};
    }
    @Secured("ROLE_ADMIN")
    @PostMapping("/")
    R<User> save(@AuthenticationPrincipal UserDetails user,@Valid @RequestBody UserCreatePara para){
        User u = userServer.create(para);
        return new R<>(){{
            setData(u);
        }};
    }

    @Secured("ROLE_ADMIN")
    @PostMapping("/reenable/{id}")
    R Reenable(@AuthenticationPrincipal UserDetails user,@PathVariable Integer id){
        userServer.reenable(id);
        return new R();
    }

    @Secured("ROLE_ADMIN")
    @DeleteMapping("/{id}")
    R delete(@AuthenticationPrincipal UserDetails user,@PathVariable Integer id){
        userServer.softDelete(id);
        return new R();
    }
    @Secured("ROLE_ADMIN")
    @PutMapping("/{id}")
    R<User> update(@AuthenticationPrincipal UserDetails user,@PathVariable Integer id,@Valid @RequestBody UserUpdatePara u){

        User user1 = userServer.update(id,u);
        return new R<User>(){{
            setData(user1);
        }};
    }
}
